import Editor from '@monaco-editor/react';
import { Typography, Container, Paper, Box, Tabs, Tab } from '@mui/material';
import React from 'react';

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

const TabPanel = (props: TabPanelProps) => {
  const { children, value, index, ...other } = props;

  return (
    <div role="tabpanel" hidden={value !== index} {...other}>
      {value === index && <Box sx={{ p: 3 }}>{children}</Box>}
    </div>
  );
};

const ReactAdvanced: React.FC = () => {
  const [value, setValue] = React.useState(0);

  const handleChange = (event: React.SyntheticEvent, newValue: number) => {
    setValue(newValue);
  };

  const hooksExample = `// Hooks示例
import React, { useState, useEffect, useCallback, useMemo } from 'react';

// useState Hook
function Counter() {
  const [count, setCount] = useState(0);
  const [step, setStep] = useState(1);

  return (
    <div>
      <p>计数: {count}</p>
      <p>步长: {step}</p>
      <button onClick={() => setCount(count + step)}>增加</button>
      <button onClick={() => setStep(step + 1)}>增加步长</button>
    </div>
  );
}

// useEffect Hook
function UserStatus({ userId }) {
  const [isOnline, setIsOnline] = useState(false);

  useEffect(() => {
    // 订阅用户状态
    const subscribe = () => {
      // 模拟API调用
      const interval = setInterval(() => {
        setIsOnline(Math.random() > 0.5);
      }, 2000);
      return () => clearInterval(interval);
    };

    const unsubscribe = subscribe();
    // 清理函数
    return () => unsubscribe();
  }, [userId]); // 依赖项数组

  return <div>{isOnline ? '在线' : '离线'}</div>;
}

// useCallback Hook
function SearchResults() {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState([]);

  const handleSearch = useCallback(
    async (searchQuery) => {
      const response = await fetch(\`/api/search?q=\${searchQuery}\`);
      const data = await response.json();
      setResults(data);
    },
    [] // 空依赖数组，因为这个函数不依赖任何props或state
  );

  return (
    <div>
      <input
        value={query}
        onChange={(e) => setQuery(e.target.value)}
      />
      <button onClick={() => handleSearch(query)}>搜索</button>
      {/* 显示结果 */}
    </div>
  );
}

// useMemo Hook
function ExpensiveCalculation({ numbers }) {
  const sum = useMemo(() => {
    console.log('计算总和...');
    return numbers.reduce((acc, curr) => acc + curr, 0);
  }, [numbers]); // 只在numbers改变时重新计算

  return <div>总和: {sum}</div>;
}`;

  const stateManagementExample = `// 使用Context进行状态管理
import React, { createContext, useContext, useReducer } from 'react';

// 创建Context
const ThemeContext = createContext();
const UserContext = createContext();

// 主题Provider组件
function ThemeProvider({ children }) {
  const [theme, setTheme] = React.useState('light');

  const toggleTheme = () => {
    setTheme(theme === 'light' ? 'dark' : 'light');
  };

  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

// 用户状态管理 - 使用useReducer
const initialState = { user: null, isLoading: false, error: null };

function userReducer(state, action) {
  switch (action.type) {
    case 'LOGIN_START':
      return { ...state, isLoading: true };
    case 'LOGIN_SUCCESS':
      return { user: action.payload, isLoading: false, error: null };
    case 'LOGIN_ERROR':
      return { ...state, error: action.payload, isLoading: false };
    case 'LOGOUT':
      return initialState;
    default:
      return state;
  }
}

function UserProvider({ children }) {
  const [state, dispatch] = useReducer(userReducer, initialState);

  const login = async (credentials) => {
    dispatch({ type: 'LOGIN_START' });
    try {
      // 模拟API调用
      const user = await fakeAuth(credentials);
      dispatch({ type: 'LOGIN_SUCCESS', payload: user });
    } catch (error) {
      dispatch({ type: 'LOGIN_ERROR', payload: error.message });
    }
  };

  const logout = () => {
    dispatch({ type: 'LOGOUT' });
  };

  return (
    <UserContext.Provider value={{ ...state, login, logout }}>
      {children}
    </UserContext.Provider>
  );
}

// 使用Context的组件
function ThemedButton() {
  const { theme, toggleTheme } = useContext(ThemeContext);
  
  return (
    <button
      style={{
        backgroundColor: theme === 'light' ? '#fff' : '#333',
        color: theme === 'light' ? '#333' : '#fff'
      }}
      onClick={toggleTheme}
    >
      切换主题
    </button>
  );
}

// 组合多个Context
function App() {
  return (
    <ThemeProvider>
      <UserProvider>
        <ThemedButton />
        <UserProfile />
      </UserProvider>
    </ThemeProvider>
  );
}`;

  return (
    <Container maxWidth="lg">
      <Box sx={{ mt: 4, mb: 4 }}>
        <Typography variant="h4" gutterBottom>
          React进阶
        </Typography>
        <Typography variant="body1" paragraph>
          在这一部分，我们将深入学习React的高级特性，包括Hooks的使用和状态管理方案。
        </Typography>
      </Box>

      <Paper sx={{ width: '100%' }}>
        <Tabs value={value} onChange={handleChange} indicatorColor="primary" textColor="primary">
          <Tab label="Hooks" />
          <Tab label="状态管理" />
        </Tabs>

        <TabPanel value={value} index={0}>
          <Typography variant="h6" gutterBottom>
            React Hooks
          </Typography>
          <Typography paragraph>
            Hooks是React
            16.8引入的新特性，它允许你在不编写class组件的情况下使用状态和其他React特性。
            以下是一些常用Hooks的示例：
          </Typography>
          <Box sx={{ mt: 2, mb: 2 }}>
            <Editor
              height="600px"
              defaultLanguage="javascript"
              defaultValue={hooksExample}
              options={{
                readOnly: true,
                minimap: { enabled: false },
              }}
            />
          </Box>
          <Typography variant="body2" color="text.secondary">
            每个Hook都有其特定的用途，理解它们的使用场景对于编写高质量的React应用至关重要。
          </Typography>
        </TabPanel>

        <TabPanel value={value} index={1}>
          <Typography variant="h6" gutterBottom>
            状态管理
          </Typography>
          <Typography paragraph>
            随着应用规模的增长，状态管理变得越来越重要。React提供了Context API用于状态管理，
            对于更复杂的场景，我们可以使用useReducer或第三方库。
          </Typography>
          <Box sx={{ mt: 2, mb: 2 }}>
            <Editor
              height="600px"
              defaultLanguage="javascript"
              defaultValue={stateManagementExample}
              options={{
                readOnly: true,
                minimap: { enabled: false },
              }}
            />
          </Box>
          <Typography variant="body2" color="text.secondary">
            Context和useReducer的组合可以处理大多数状态管理需求。对于更复杂的场景，
            可以考虑使用Redux或MobX等状态管理库。
          </Typography>
        </TabPanel>
      </Paper>
    </Container>
  );
};

export default ReactAdvanced;
